from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.core.cache import cache
from django.utils import timezone
from .models import Category, Product

@receiver([post_save, post_delete], sender=Category)
def handle_category_change(sender, instance, **kwargs):
    """
    处理分类数据变更的信号
    """
    cache_keys = [
        'category_all_v1',     # list接口的缓存
        'category_choices_v1', # choices接口的缓存
        'category_tree_v1',    # 树形结构缓存
    ]
    for key in cache_keys:
        cache.delete(key)
    
    # 记录最后更新时间
    cache.set('category_last_updated', timezone.now().isoformat())
    print(f"[Cache] Category cache cleared at {timezone.now()}")

@receiver([post_save, post_delete], sender=Product)
def handle_product_category_change(sender, instance, **kwargs):
    """
    处理商品分类关联变更的信号
    """
    if instance.category:
        cache_key = f'category_products_{instance.category.id}'
        cache.delete(cache_key)
        print(f"[Cache] Products cache cleared for category {instance.category.id}")